package shark.picture.utils.other;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfWriter;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;

public class WordToPdfWithPOI {
    public static void main(String[] args) {
        try {
            // 读取 Word 文档
            FileInputStream fis = new FileInputStream("E:\\\\shark\\\\需求文档\\\\2025-08-27 直通车\\\\申请单模板.docx");
            XWPFDocument document = new XWPFDocument(fis);

            // 创建 PDF 文档
            Document pdfDoc = new Document();
            PdfWriter.getInstance(pdfDoc, Files.newOutputStream(Paths.get("output.pdf")));
            pdfDoc.open();

            // 遍历 Word 文档的段落
            for (XWPFParagraph paragraph : document.getParagraphs()) {
                StringBuilder text = new StringBuilder();
                // 遍历段落中的文本运行对象
                for (XWPFRun run : paragraph.getRuns()) {
                    text.append(run.getText(0));
                }
                // 将段落文本添加到 PDF 文档中
                Paragraph pdfParagraph = new Paragraph(text.toString());
                pdfDoc.add(pdfParagraph);
            }

            // 关闭文档和流
            pdfDoc.close();
            document.close();
            fis.close();

            System.out.println("Word 转 PDF 成功！");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Word 转 PDF 失败：" + e.getMessage());
        }
    }
}
